﻿using System.Collections.Generic;
using System.IO;

namespace Smart.Model
{
    public static class ABInfoHelper
    {
        public static ABInfo[] GetABInfos(this byte[] contents,int offset)
        {
            int pos = offset;
            int cnt = contents.ReadInt(ref pos);
            ABInfo[] aBInfos = new ABInfo[cnt];
            for(int i = 0; i < cnt;++i)
            {
                var abInfo = new ABInfo();
                aBInfos[i] = abInfo;
                abInfo.bundleName = contents.ReadString(ref pos);
                abInfo.md5 = contents.ReadString(ref pos);
                abInfo.crc = (uint)contents.ReadInt(ref pos);
                int dependCnt = contents.ReadInt(ref pos);
                var dependencies = new string[dependCnt];
                for(int j = 0; j < dependCnt;++j)
                {
                    dependencies[j] = contents.ReadString(ref pos);
                }
                abInfo.dependencies = dependencies;
            }
            return aBInfos;
        }

        public static Dictionary<string,ABInfo> Make(this ABInfo[] aBInfos)
        {
            Dictionary<string, ABInfo> dic = new Dictionary<string, ABInfo>(aBInfos.Length);
            for(int i = 0;i<aBInfos.Length;++i)
            {
                dic.Add(aBInfos[i].bundleName, aBInfos[i]);
            }
            return dic;
        }

        public static void Write(this Stream stream, ABInfo[] abInfos)
        {
            if(null != stream && null != abInfos)
            {
                int cnt = abInfos.Length;
                stream.Encode(cnt);
                for (int i = 0; i < cnt; ++i)
                {
                    var abInfo = abInfos[i];
                    stream.Encode(abInfo.bundleName);
                    stream.Encode(abInfo.md5);
                    stream.Encode(abInfo.crc);
                    var dependencies = abInfo.dependencies;
                    int dependCnt = dependencies.Length;
                    stream.Encode(dependCnt);
                    for (int j = 0; j < dependCnt; ++j)
                    {
                        stream.Encode(dependencies[j]);
                    }
                }
            }
        }
    }
}